package com.homelock.service;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.homelock.common.util.HttpClient;
import com.homelock.entity.UserWechat;
import com.homelock.mapper.UserWechatMapper;

@Service
public class WeChatService {
  private static final String WECHAT_AUTH_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=wx36a92d841d03fdaf&secret=93819b0a9e8fa19c2d3d9e52c26710c5&grant_type=authorization_code&js_code=";
  private static final Logger logger = LoggerFactory.getLogger(WeChatService.class);
  @Autowired 
  private UserWechatMapper userWechatMapper;
  
  public UserWechat weChatAuth(String jsCode) {
    UserWechat record = new UserWechat();
    String result = HttpClient.doGet(WECHAT_AUTH_URL + jsCode);
    JSONObject obj = JSONObject.parseObject(result);
    String errcode = obj.getString("errcode");
    if(StringUtils.isNoneBlank(errcode) && "0 ".equals(errcode)) {
      String openid = obj.getString("openid");
      //String sessionKey = obj.getString("session_key");
      //微信用户在开放平台的唯一标识符
      String unionid = obj.getString("unionid");
      //判断是否微信首次登陆
      UserWechat rec = userWechatMapper.selectByUnionid(unionid);
      if(null == rec) {
        record.setWxOpenid(openid);
        record.setWxUnionid(unionid);
        record.setCreateDate(new Date());
        record.setState(10);
        userWechatMapper.insertSelective(record);
      }else {
        record = rec;
      }
//      request.getSession().setAttribute("wechatUser", record);
    }else {
      String errmsg = obj.getString("errmsg");
      logger.error("微信登录凭证校验异常，errmsg="+errmsg);
    }
    return record;
  }
}
